package com.cr.crsystem.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cr.crsystem.common.base.constant.CommonConstant;
import com.cr.crsystem.system.entity.Car;
import com.cr.crsystem.system.entity.Rent;
import com.cr.crsystem.system.entity.UserRent;
import com.cr.crsystem.system.mapper.CarMapper;
import com.cr.crsystem.system.service.CarService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cr.crsystem.system.service.RentService;
import com.cr.crsystem.system.service.UserRentService;
import com.cr.crsystem.system.vo.CarVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author su
 * @since 2022-06-21
 */
@Service
public class CarServiceImpl extends ServiceImpl<CarMapper, Car> implements CarService {

    @Autowired
    private RentService rentService;
    @Autowired
    private UserRentService userRentService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteCar(Integer id) {
        List<Rent> rents = rentService.list(new QueryWrapper<Rent>().lambda().eq(Rent::getCarId, id));
        List<Integer> rentIds = rents.stream().map(Rent::getId).collect(Collectors.toList());
        //删除订单关系
        if (rentIds.size() > 0) {
            userRentService.remove(new QueryWrapper<UserRent>().in("rent_id", rentIds));
        }
        //删除订单
        rentService.remove(new QueryWrapper<Rent>().lambda().eq(Rent::getCarId, id));
        //删除汽车
        baseMapper.deleteById(id);
        return true;
    }

    @Override
    public List<CarVo> queryUnApproveCar(String status) {
        List<CarVo> carVos = baseMapper.queryUnApproveCar(status);
        return carVos;
    }

    @Override
    public List<CarVo> queryApproveCar(String[] statusList) {
        List<CarVo> carVos = baseMapper.queryApproveCar(statusList);
        return carVos;
    }

    @Override
    public boolean edit(Car car) {
        Car oldCar = baseMapper.selectById(car.getId());
        if (oldCar.getStatus().equals(car.getStatus())) {
            //修改车辆信息需要重新申请
            car.setStatus(CommonConstant.APPROVE_STATUS_0);
        }
        baseMapper.updateById(car);
        return true;
    }
}
